package com.godyao.mall.async;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author godyao
 * @date 2022/4/5
 */
@EnableAsync
@EnableScheduling
@Configuration
public class AsyncAutoConfig {

    /**
     * 配置线程池参数
     * @return
     */
    @Bean
    public AsyncTaskExecutor asyncTaskExecutor() {
        //new ThreadPoolExecutor()
        final ThreadPoolTaskExecutor poolTaskExecutor = new ThreadPoolTaskExecutor();
        poolTaskExecutor.setCorePoolSize(4);
        poolTaskExecutor.setMaxPoolSize(6);
        // 线程最大空闲时间 秒
        poolTaskExecutor.setKeepAliveSeconds(120);
        // 设置队列容量 根据容量来使用对应的队列
        //protected BlockingQueue<Runnable> createQueue(int queueCapacity) {
        //    return (BlockingQueue)(queueCapacity > 0 ? new LinkedBlockingQueue(queueCapacity) : new SynchronousQueue());
        //}
        poolTaskExecutor.setQueueCapacity(40);
        // 拒绝策略 这里使用调用者线程执行
        poolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        poolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        return poolTaskExecutor;
    }
}
